package com.wm.machine.baselibrary.utils.imageutils;


import android.content.Context;
import android.support.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.Registry;
import com.bumptech.glide.load.engine.bitmap_recycle.LruBitmapPool;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.module.GlideModule;
import com.wm.machine.baselibrary.utils.imageutils.https.HttpsUtil;
import com.wm.machine.baselibrary.utils.imageutils.https.OkHttpUrlLoader;

import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;

/**
 * 混淆的话，要在proguard-rules.pro添加-keepnames class * 完整包名.CustomCachingGlideModule
 * create by wentong.chen 2018.1.30
 * 功能：图片缓存设置
 */
public class CustomCachingGlideModule implements GlideModule {
  private final String cacheFileName = "glideCache";
  private final int cacheSize100MegaBytes = 104857600;

  /**
   * 设置图片缓存的配置参数
   * 
   * @param context 上下文
   * @param builder GlideBuilder
   */
  @Override
  public void applyOptions(Context context, GlideBuilder builder) {
    // 设置磁盘缓存为100M，缓存在内部缓存目录
    builder.setDiskCache(
        new ExternalCacheDiskCacheFactory(context, cacheSize100MegaBytes));

    // builder.setDiskCache();//自定义磁盘缓存
    //
    // builder.setMemoryCache();//自定义内存缓存
    //
    // builder.setBitmapPool(); //自定义图片池
    //
    // builder.setDiskCacheService();//自定义本地缓存的线程池
    //
    // builder.setResizeService();//自定义核心处理的线程池
    //
    // builder.setDecodeFormat();//自定义图片质量
    // 20%大的内存缓存作为 Glide 的默认值

    MemorySizeCalculator calculator = new MemorySizeCalculator.Builder(context).build();
    int defaultMemoryCacheSize = calculator.getMemoryCacheSize();
    int defaultBitmapPoolSize = calculator.getBitmapPoolSize();

    int customMemoryCacheSize = (int) (1.2 * defaultMemoryCacheSize);
    int customBitmapPoolSize = (int) (1.2 * defaultBitmapPoolSize);

    builder.setMemoryCache(new LruResourceCache(customMemoryCacheSize));
    builder.setBitmapPool(new LruBitmapPool(customBitmapPoolSize));
  }

  @Override
  public void registerComponents(@NonNull Context context, @NonNull Glide glide,
      @NonNull Registry registry) {
    OkHttpClient okhttpClient = new OkHttpClient.Builder()
            .retryOnConnectionFailure(true) // 设置出现错误进行重新连接。
            .connectTimeout(15, TimeUnit.SECONDS)
            .readTimeout(60 * 1000, TimeUnit.MILLISECONDS)
            .sslSocketFactory(HttpsUtil.getSslSocketFactory())
            .hostnameVerifier(new HttpsUtil.UnSafeHostnameVerifier())
            .build();
    registry.replace(GlideUrl.class, InputStream.class,
            new OkHttpUrlLoader.Factory(okhttpClient));
  }

}
